//
//  SLImagePreview.m
//  SoccerLottery
//
//  Created by chuanshuangzhang chuan shuang on 15/12/24.
//  Copyright © 2015年 chuanshuangzhang. All rights reserved.
//

#import "SLImagePreview.h"
#import "UIImageView+WebCache.h"
@implementation SLImagePreview

- (id)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame]){
        [self addSubview:self.scrollView];
        _pageControl = [[UIPageControl alloc]init];
        _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
        _pageControl.bounds = CGRectMake(0, 0, 20*_pageControl.numberOfPages, 20);
        _pageControl.center = CGPointMake(frame.size.width/2.0, frame.size.height*0.9);
        _pageControl.currentPage = 0;
        _pageControl.enabled = NO;
        [self addSubview:_pageControl];
        [self setImageArray:@[@"preview"]];
    }
    return self;
}
- (UIScrollView *)scrollView{
    if(_scrollView == nil){
        _scrollView = [[UIScrollView alloc]initWithFrame:self.bounds];
        _scrollView.pagingEnabled = YES;
        _scrollView.bounces = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.delegate = self;
    }
    return _scrollView;
}
- (void)setImageArray:(NSArray *)imageArray
{
    if(imageArray.count <=0){
        return;
    }
    
    if(imageArray.count > 1){
      _pageControl.numberOfPages = imageArray.count;
    }
    _imageArray = [NSArray arrayWithArray:imageArray];
    self.scrollView.contentSize = CGSizeMake(self.frame.size.width * imageArray.count, self.frame.size.height);
    for (UIView *view in self.scrollView.subviews) {
        [view removeFromSuperview];
    }
    for (NSInteger idx = 0; idx < imageArray.count; idx ++) {
        id obj = imageArray[idx];
        NSString *imagUrl;
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(idx*self.frame.size.width, 0, self.frame.size.width,self.frame.size.height)];
        if([obj isKindOfClass:[NSString class]]){
            imagUrl = obj;
            imageView.image = [UIImage imageNamed:imagUrl];
        }else {
            imagUrl = obj[@"ImgUrl"];
            [imageView sd_setImageWithURL:[NSURL URLWithString:imagUrl] placeholderImage:[UIImage imageNamed:@"preview"]];
        }
        imageView.contentMode = UIViewContentModeScaleToFill;
        imageView.userInteractionEnabled = YES;
        imageView.tag = idx + 1;
        [self.scrollView addSubview:imageView];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    int page = scrollView.contentOffset.x / scrollView.bounds.size.width;
    _pageControl.currentPage = page;
}

@end
